package com.riekoff.particlecubeworld.player;

import cc.creativecomputing.control.CCControl;
import cc.creativecomputing.events.CCListenerManager;
import cc.creativecomputing.util.logging.CCLog;

public class AGlobalTimingController {

	@CCControl(name = "duration scale", min = 0.1f, max = 110f)
	private float _cDuration = 1f;
	
	@CCControl(name = "direct control")
	private boolean _cControlDirect = true;
	
	@CCControl(name = "direct progress", min = 0, max = 1.0f)
	private float _cDirectProgress = 10;
	
	private CCListenerManager<AGlobalTimingProgressListener> _myEvents = CCListenerManager.create(AGlobalTimingProgressListener.class);
	
	private int progressSum (int[] theSteps) {
		int ret = 0;
		for (int i=1; i<theSteps.length; i+=2) {
			ret += theSteps[i];
		}
		return ret;
	}
	int steps[] = {0};
	
	float _myProgress = 0f;
	
	
	public AGlobalTimingController (int duration) {
	}
	
	public void reset (int[] theSteps){
		steps = theSteps;
		sum = progressSum(steps);
	}
	
	int cnt = 0;
	float dT = 0f;
	float sum = progressSum(steps);
	
	public void update(final float theDeltaTime){
		if(_cControlDirect){
			_myEvents.proxy().progress(_cDirectProgress);
			_myEvents.proxy().update(theDeltaTime);
			return;
		}

		dT += theDeltaTime * _cDuration;
		if (dT>steps[cnt]) {
			dT -= steps[cnt];
			cnt  = (cnt += 1)%steps.length;
		}
		if (cnt%2==1) {
			_myProgress += theDeltaTime * _cDuration / steps[cnt] / steps.length  * 2;
		}
		if (cnt==0) {
			_myProgress = 0f;
		}
		if(_myProgress >= 1){
			cnt = 0;
			_myEvents.proxy().onRestart();
			CCLog.info("restart");
		}
		
		_myEvents.proxy().progress(_myProgress);
		_myEvents.proxy().update(theDeltaTime);
	}
	
	public CCListenerManager<AGlobalTimingProgressListener> events(){
		return _myEvents;
	}
}
